<!--
 * @Author: ChunLai
 * @Date: 2022-01-17 11:24:24
 * @LastEditTime: 2025-09-05 08:53:15
 * @Description: 签名分享---订单确认页
 * @FilePath: \02.bldinsure\src\views\sign\preact.vue
-->
<template>
  <div class="bill_sure_page">
    <!-- 业务员信息(双录展示) -->
    <DoubleRecord />
    <div class="mt10" id="cash_module">
      <RiskPlanModule :cashShow="true" />
    </div>
    <InsureInfos />
    <div class="fileList mt10">
      <!-- 单文件签名 -->
      <template v-if="configClauses.length > 0">
        <van-cell
          :title="item.title"
          is-link
          v-for="item in configClauses"
          :key="`sign_file${item.title}`"
          @click="openCfgRead($event, item)"
        >
          <span :class="item.signed == '1' ? 'ftc12' : 'ftc13'">
            {{ item.signed == "1" ? "已签名" : "未签名" }}
          </span>
        </van-cell>
      </template>
      <!-- 统一签名 -->
      <template v-if="clauseFiles.length > 0">
        <van-cell
          :title="item.title"
          is-link
          v-for="(item, index) in clauseFiles"
          :key="`must_read${index}`"
          @click="openRead($event, item, index)"
        >
          <span :class="item.read == '1' ? 'ftc12' : 'ftc13'">
            {{ item.read == "1" ? "已查看" : "未查看" }}
          </span>
        </van-cell>
      </template>
      <template v-if="hasTranscribe">
        <van-cell
          title="授权和声明"
          is-link
          key="copy_cell"
          @click="goCopyPage"
        >
          <span :class="copyFinish == '1' ? 'ftc12' : 'ftc13'">
            {{ copyFinish ? "已抄录" : "未抄录" }}
          </span>
        </van-cell>
      </template>
      <ProtocolsReading id="protocols_module" />
    </div>
    <SignatureBoard ref="mysign" @uploadSing="signDoneCheck" v-if="openSign" />
    <FooterBtns
      btnNum="1"
      :rightText="rightText"
      @saveForm="startSign"
    ></FooterBtns>

    <!-- 接口文档阅读弹窗 -->
    <ApiFileDisplay
      ref="apiFilePop"
      @handleClick="setFileReadStatus"
      v-if="showConfirmFile"
    />
    <SelfValidatePop ref="selfValidRef" />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import RiskPlanModule from "@/components/RiskPlanModule";
import InsureInfos from "./components/InsureInfos";
import ProtocolsReading from "./components/ProtocolsReading";
import DoubleRecord from "./components/DoubleRecord";
import ApiFileDisplay from "./components/ApiFileDisplay";
import SelfValidatePop from "./components/SelfValidatePop";
import { rebackUrlPath } from "@/methods/format.js";

export default {
  name: "BillSignPreSurePage",
  data() {
    return {
      showConfirmFile: false,
      copyFinish: false,
      fileIndex: 0,
      clauseFiles: [], //接口返回文档
      configClauses: [],
      resValue: "0", //签名结果状态
      apiError: "",
    };
  },
  components: {
    RiskPlanModule,
    InsureInfos,
    DoubleRecord,
    ApiFileDisplay,
    SelfValidatePop,
    ProtocolsReading,
  },
  computed: {
    ...mapGetters({
      apiBbrMult: "insert/apiBbrMult",
      applicant: "insert/applicant",
      agentInfo: "agent/agentInfo",
      openSign: "filesign/openSign",
      showedRisks: "risks/showedRisks", //投保条款
      userObj: "filesign/userObj",
      userType: "filesign/userType",
      interLinkSign: "page/interLinkSign",
      singleFileSign: "page/singleFileSign",
      fileSignUls: "page/fileSignUls",
      tbrPrvinCapital: "insert/tbrPrvinCapital",
      transcribeProducts: "page/transcribeProducts",
      selfInsuredRegions: "dictionary/selfInsuredRegions",
      readFinish: "readings/wholeFinish",
      showCashTable: "page/showCashTable",
      checkCashRead: "page/checkCashRead",
      minorAge: "page/minorAge",
      ocrFaceVerify: "page/ocrFaceVerify",
    }),
    readApiFinish() {
      let res = true;
      const len = this.clauseFiles.length;
      if (len > 0) {
        for (let i = 0; i < len; i++) {
          const item = this.clauseFiles[i];
          if (item.read != "1") {
            res = false;
            break;
          }
        }
      }
      return res;
    },
    hasTranscribe() {
      let res = false;
      if (this.transcribeProducts.length > 0) {
        if (
          this.transcribeProducts.includes(this.mainRiskCode) &&
          this.userType == "1"
        ) {
          res = true;
        }
      }
      return res;
    },
    rightText() {
      let res = "签名";
      if (this.fileSignUls.length > 0) {
        res = "签名确认";
      }
      return res;
    },
    cfgSignFinish() {
      let res = true;
      const len = this.configClauses.length;
      for (let i = 0; i < len; i++) {
        const item = this.configClauses[i];
        if (item.signed != "1") {
          res = false;
          break;
        }
      }
      return res;
    },
    isShareSign() {
      let res = false;
      if (this.$getDataFromUrl("share") == "1") {
        res = true;
      }
      return res;
    },
  },
  watch: {},
  async created() {
    const querys = this.$route.query;
    if (querys.status && querys.status == "1") {
      this.resValue = "1";
    }
    this.$store.dispatch("readings/initFilesList");
    this.$store.commit("filesign/SET_STATE_CONFIG", {
      openSign: false,
    });
    let ctype = this.userType;
    // 分享页初始化签名信息
    if (this.$getDataFromUrl("share") == "1") {
      let msg = {},
        uname = "";
      const utype = this.$getDataFromUrl("utype"),
        uindex = this.$getDataFromUrl("uindex") || 0;
      if (utype === "1") {
        msg = this.applicant;
      } else if (utype === "2") {
        msg = this.apiBbrMult[uindex * 1];
      } else if (utype === "3") {
        msg = this.agentInfo;
      }
      uname = `${msg.name}`;
      if (utype == "2") {
        const bbrUser = JSON.parse(JSON.stringify(this.apiBbrMult[uindex * 1]));
        if (
          this.$GlobalFuns.isMinorBaby(bbrUser) &&
          bbrUser.guardianIdNo &&
          bbrUser.guardianName
        ) {
          msg = {
            name: bbrUser.guardianName,
            idNum: bbrUser.guardianIdNo,
          };
          uname = bbrUser.guardianName;
        }
      }
      this.$store.commit("filesign/SET_SIGN_OBJ", msg);
      this.$store.commit("filesign/SET_STATE_CONFIG", {
        signName: `${uname}`,
        userType: `${utype}`,
      });
      if (this.$getDataFromUrl("status") == "1") {
        this.resValue = "1";
      }
      ctype = utype;
    }
    // 1.判断是否需要人脸识别:是否通过
    if (process.env.VUE_APP_PRODFLAG == "wxou" || this.ocrFaceVerify) {
      this.describeFaceVerify();
    }
    // 百年
    if (this.fileSignUls.length > 0) {
      const len = this.fileSignUls.length;
      for (let i = 0; i < len; i++) {
        const item = this.fileSignUls[i];
        item.signed = "0";
        const kehuArr = item.kehuType || ["1", "2"];
        item.show = kehuArr.includes(ctype);
        if (item.fileType == "8") {
          // 重庆问卷
          item.show = this.tbrPrvinCapital === "500000";
        } else if (item.fileType == "10") {
          // 可回溯
          const provns = this.selfInsuredRegions || [];
          item.show = provns.includes(this.tbrPrvinCapital);
        }
      }
      let list = this.fileSignUls.filter((ele) => ele.show);
      this.getSignImgList(list);
    }
    this.initFileList();
  },
  mounted() {
    // 抄录
    if (this.hasTranscribe) {
      this.getTranscribeImg();
    }
  },
  methods: {
    /**腾讯云实人认证---查询接口 */
    describeFaceVerify() {
      return new Promise((reslove, reject) => {
        this.$store.commit("updateLoad", true);
        let params = {
          ...this.apiComParams,
          idNum: this.userObj.idNum || "",
          type: "tb",
        };
        this.$http
          .post("/ms-insure/api/common/queryFaceVerify", params, {
            json: true,
          })
          .then(({ data }) => {
            this.$store.commit("updateLoad", false);
            if (data.code != "1") {
              reslove("0");
              this.$nextTick(() => {
                this.$refs.selfValidRef.initModule();
              });
            } else {
              reslove("1");
            }
          })
          .catch((err) => {
            reslove("0");
            this.$store.commit("updateLoad", false);
          });
      });
    },
    // 初始化文件列表 + 回显赋值
    initFileList() {
      this.clauseFiles = [];
      if (this.compEngName == "bainian") {
        if (this.userType != "1") return;
      }
      this.$store.commit("updateLoad", true);
      this.apiError = "";
      this.$http
        .post("/ms-insure/api/common/confirmBook", this.apiComParams, {
          json: true,
        })
        .then(({ data }) => {
          // console.log(data);
          this.$store.commit("updateLoad", false);
          if (data.code == "1") {
            const files = data.confirmBooks || [];
            if (files.length > 0) {
              // 签名完成的，免阅读
              if (this.resValue == "1") {
                const len = files.length;
                for (let i = 0; i < len; i++) {
                  const item = files[i];
                  item.read = "1";
                }
                this.$store.dispatch("readings/setWholeFinish");
              }
              this.clauseFiles = files;
            }
          } else {
            this.apiError = data.msg;
            this.$msAlert(data.msg);
          }
        })
        .catch((err) => {
          this.$store.commit("updateLoad", false);
        });
    },
    openRead($event, item, index) {
      this.showConfirmFile = true;
      this.fileIndex = index;
      this.$nextTick(() => {
        this.$refs.apiFilePop.initModule(item);
      });
    },
    goCopyPage() {
      this.$router.push("/transcribe");
    },
    setFileReadStatus() {
      this.$set(this.clauseFiles[this.fileIndex], "read", "1");
      this.showConfirmFile = false;
    },
    startSign() {
      if (this.apiError) return this.$msAlert(this.apiError);
      let target = "";
      // 利安现价必读
      if (this.showCashTable && this.checkCashRead) {
        const read_stu = this.$getMessage("is_read_cash");
        if (read_stu != "1") {
          target = document.querySelector("#cash_module");
          target.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
          return this.$toast("请查看《现金价值表》");
        }
      }
      if (!this.readApiFinish || !this.readFinish) {
        target = document.querySelector("#protocols_module");
        target.scrollIntoView({
          behavior: "smooth",
          block: "start",
        });
        return this.$toast("请完成以上条款的阅读");
      }
      if (this.hasTranscribe && !this.copyFinish)
        return this.$toast("请完成授权声明的抄录");
      // 百年
      if (this.singleFileSign) {
        if (this.fileSignUls.length > 0) {
          if (!this.cfgSignFinish) return this.$toast("请完成以上文件的签名");
        }
        if (this.clauseFiles.length > 0) {
          this.$store.commit("filesign/SET_STATE_CONFIG", {
            openSign: true,
          });
          return;
        }
        this.saveSignRes();
      } else {
        this.$store.commit("filesign/SET_STATE_CONFIG", {
          openSign: true,
        });
      }
    },
    signDoneCheck() {
      if (this.singleFileSign) {
        return this.saveSignRes();
      }
      this.signDoneNext();
    },
    signDoneNext() {
      if (this.isShareSign) {
        this.$router.push("/shareres");
      } else {
        this.$router.push("/billsure");
      }
    },
    openCfgRead($event, item) {
      this.getSignLinkApi(item.fileType);
    },
    getSignLinkApi(fileType) {
      let utype = this.userType;
      if (
        ["1", "2"].includes(utype) &&
        this.apiBbrMult[0].relationToAppnt == "4"
      ) {
        utype = "0";
      }
      const backUrl = `${rebackUrlPath()}`;
      let params = {
        ...this.apiComParams,
        imgType: `${utype}`, //0投被保人签字类型 1投保人签字类型 2被保人签字类型,3代理人
        fileType: fileType, //0 投保确认书 8重庆问卷 13回执链接 7银行变更授权书地址 2.免除保险人责任条款说明 15.承保前撤单签名，10可回溯情况销售人员告知书签名
        isShare: `${this.isShareSign ? "1" : "0"}`, //是否分享，0不分享，1分享
        successUrl: `${backUrl}`,
        failUrl: `${backUrl}`,
      };

      this.$store
        .dispatch("apis/comAdminApiRequest", {
          apiParams: params,
          apiName: "getSignLink",
          toast: true,
        })
        .then(({ data }) => {
          if (data.code == "1") {
            window.location.href = data.url;
          }
        });
    },
    getSignImgList(lists) {
      this.imgList = [];
      this.$store.commit("updateLoad", true);
      let utype = this.userType;
      if (
        ["1", "2"].includes(utype) &&
        this.apiBbrMult[0].relationToAppnt == "4"
      ) {
        utype = "0";
      }
      let params = {
        ...this.apiComParams,
        imgType: `${utype}`,
      };
      this.$store
        .dispatch("apis/comAdminApiRequest", {
          apiParams: params,
          apiName: "queryImgList",
          toast: true,
        })
        .then((data) => {
          if (data.code == "1") {
            if (data.imgList.length > 0) {
              const len = lists.length;
              for (let i = 0; i < len; i++) {
                const img = lists[i],
                  fdObj = data.imgList.find((ele) => ele.type == img.fileType);
                if (fdObj && fdObj.imgUrl == "1") {
                  img.signed = "1";
                }
              }
              if (this.hasTranscribe) {
                const fdCopy = data.imgList.find((ele) => ele.type == "88");
                if (fdCopy && fdCopy.imgUrl == "1") {
                  this.copyFinish = true;
                }
              }
            }
            this.configClauses = lists;
            if (this.resValue == "1") {
              this.$store.dispatch("readings/setWholeFinish");
            }
          }
        });
    },
    getTranscribeImg() {
      let params = {
        ...this.apiComParams,
        imgType: `19`,
      };
      this.$store
        .dispatch("apis/comAdminApiRequest", {
          apiParams: params,
          apiName: "queryImgList",
          toast: true,
        })
        .then((data) => {
          if (data.code == "1") {
            if (data.imgList.length > 0) {
              const fdCopy = data.imgList.find((ele) => ele.type == "0");
              if (fdCopy) {
                this.copyFinish = true;
              }
            }
          }
        });
    },
    // 单文件签名结果保存
    saveSignRes() {
      let ulabel = "";
      if (this.userType == "1") {
        ulabel = "tbr";
      } else if (this.userType == "2") {
        ulabel = "bbr";
      } else if (this.userType == "3") {
        ulabel = "dlr";
      }
      this.$store.commit("updateLoad", true);
      let params = {
        ...this.apiComParams,
        key: `${ulabel}SignFlag`,
        value: "1",
      };
      this.$store
        .dispatch("apis/comAdminApiRequest", {
          apiParams: params,
          apiName: "updateOrderFlag",
          toast: true,
        })
        .then((data) => {
          this.signDoneNext();
        });
    },
  },
};
</script>

<style lang="less" scoped>
.bill_sure_page {
  padding-bottom: 100px;
}

.mode1 {
  padding: 10px 12px 17px 12px;
  background: #ffffff;

  .mode1_value {
    font-size: 15px;
    color: #343434;
    font-weight: 600;
    margin-left: 12px;
  }

  .mode1_v2 {
    width: calc(100% - 26px);
    color: #242424;
    font-weight: 400;
    padding: 10px;
    line-height: 1.5;
    border-radius: 0px 10px 10px 10px;
    background: #fff4e8;
    margin-left: 12px;
    margin-top: 8px;
  }
}

/deep/.van-cell__title {
  flex: 2;
}
</style>
